/* log.c */

#define _XOPEN_SOURCE

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#include "log.h"

logfile_t *logfile_open(const char *path){
	char buf[512];
	FILE *fp = NULL;
	logfile_t *file;
	log_t log;
	if((fp = fopen(path, "a+"))== NULL ){
		return NULL;
	}
	if((file = (logfile_t *)malloc(sizeof(logfile_t))) == NULL){
		fclose(fp);
		return NULL;
	}
	file->log_file = fp;
	//determine the max order id and log num
	file->log_num = 0;
	file->max_order_id = 0;
	fseek(file->log_file, 0, SEEK_SET);
	while(fgets(buf,512, fp) != NULL){
		if(parse_log(&log, buf)!= 0)
			continue;
		file->log_num++;
		
		file->max_order_id = file->max_order_id >= log.order_id ? file->max_order_id:log.order_id;
	}
	return file;
}

int logfile_close(logfile_t * file){
	fclose(file->log_file);
	free(file);
	return 0;
}

int add_log(logfile_t *file, log_t *log){
	char time1[64];
	char time2[64];
	struct tm tim;
	
	gmtime_r(&(log->order_time), &tim);
	strftime(time1, 64,"%Y-%m-%d %H:%M:%S",&tim);
	gmtime_r(&(log->time), &tim);
	strftime(time2, 64,"%Y-%m-%d %H:%M:%S",&tim);
	
	fprintf(file->log_file, "%d\t%s\t%d\t%s\t%s\t%d\t%s\n", 
			log->order_id,
			time1,
			log->user_id,
			log->train_no,
			time2,
			log->ticket_num,
			log->other);
	fflush(file->log_file);
	return 0;
}



int parse_log(log_t * lg, const char * line){
	static char buf[512];
	char *order_id;
	char *order_time;
	char *usr_id;
	char *train_no;
	char *time;
	char *ticket_num;
	char *other;
	struct tm tim1;
	struct tm tim2;
	strcpy(buf, line);
	order_id = buf;
	if((order_time = strstr(order_id,"\t")) != NULL){
		printf(".");
		*order_time = '\0';
		order_time += 1;
	}else return -1;
	if((usr_id = strstr(order_time,"\t")) != NULL){
		*usr_id = '\0';
		usr_id += 1;
	}else return -1;
	if((train_no= strstr(usr_id,"\t")) != NULL){
		*train_no = '\0';
		train_no += 1;
	}else return -1;
	if((time = strstr(train_no,"\t")) != NULL){
		*time = '\0';
		time += 1;
	}else return -1;
	if((ticket_num = strstr(time,"\t")) != NULL){
		*ticket_num = '\0';
		ticket_num += 1;
	}else return -1;
	if((other = strstr(ticket_num,"\t")) != NULL){
		*other = '\0';
		other += 1;
	}else return -1;
	
	other[strlen(other)-1] = '\0';
	lg->order_id = atoi(order_id);
	strptime(order_time,"%Y-%m-%d %H:%M:%S",&tim1);
	lg->order_time= mktime(&tim1);
	lg->user_id = atoi(usr_id);
	strcpy(lg->train_no, train_no);
	strptime(time,"%Y-%m-%d %H:%M:%S",&tim2);
	lg->time = mktime(&tim2);
	lg->ticket_num = atoi(ticket_num);
	strcpy(lg->other, other);
	return 0;
}

